<?php
namespace Hive;
/**
 * Install Object, to install the standard Hive Bundle
 * 
 * 
 */
class Install {
	
	/**
	 * 
	 * Admin User
	 * @var \Hive\User
	 */
	private $_user = null;
	
	/**
	 * Cloud Name Space
	 * @var string
	 */
	private $_cloudName = null;
	
	/**
	 * 
	 * Cloud Directory Path
	 * @var string
	 */
	private $_cloudDirectory = null;

	/**
	 * Application Database Name
	 * @var string
	 */
	private $_appDatabaseName = null;
	
	/**
	 * Application Database User Name
	 * @var string
	 */
	private $_appDatabaseUserName = null;
	
	/**
	 * Application Database User Name
	 * @var string
	 */
	private $_appDatabaseSecureKey = null;
	
	/**
	 * 
	 * Enter description here ...
	 * @param unknown_type $user
	 * 
	 */
	public function __construct($user) {
		// Admin User that initialize the installation
		$this->_user = $user;
	}
	
	/**
	 * Execute Installation
	 * 
	 * @throws \Exception
	 */
	public function execute($status) {
		if(!$this->_user->exists()) {
			throw new \Exception('User does not exist');
		}
		$status->start();
		// 1. Load User Specific Information
		$this->_cloudName = $this->_user->cloudName();
		// 2. Create Database
		$this->_createApplicationDatabase($status);
		// 3. Create Cloud Directory
		$status->nextStep(1);
		$cloudDirectory = _CLOUD_DIRECTORY_.$this->_cloudName;
		if(!is_dir($cloudDirectory)) {
			mkdir($cloudDirectory, 0700, true);
		} else {
			throw new \Exception("Directory $cloudDirectory already exists");
		}
		$this->_cloudDirectory = $cloudDirectory.DIRECTORY_SEPARATOR;
		// 4. Create Configuration file
			// 4.1 Index.php
			$this->_buildIndexFile();
			// 4.2 config & const files
			$status->nextStep(1);
			$this->_buildConfigFiles();
		// 5. Create All usefull directories
		$this->_createApplicationDirectories();
	}
	
	/**
	 * 
	 * Create Application DataBase
	 */
	private function _createApplicationDatabase($status) {
		$targetDatabaseName = 'hive_'.$this->_cloudName;
		$keys = preg_split('/:/',\Fox\Utilities::detokenize(_CLOUD_CORE_DB_SECURE_KEY_));
		$host = _CLOUD_DB_HOST_;
		$connexion = new \PDO("mysql:host=$host", $keys[0], $keys[1]);
		// Check If DataBase Exists (should never happen)
		$req = "SELECT SCHEMA_NAME FROM information_schema.SCHEMATA WHERE SCHEMA_NAME = '".$targetDatabaseName."'";
		$stmt = $connexion->query($req);
		if ($stmt->rowCount() == 0) {
			// Create Database
			$req = 'CREATE DATABASE IF NOT EXISTS '.$targetDatabaseName;
			$connexion->prepare($req)->execute();
			$sql = file_get_contents(_CLOUD_RESSOURCES_DIRECTORY_.'schema.sql');
			$connexion->query('use ' . $targetDatabaseName);
			$connexion->query($sql);
			// Fill with default data
			$sql = file_get_contents(_CLOUD_RESSOURCES_DIRECTORY_.'default_data.sql');
			$connexion->query($sql);
			/*
			$username = $this->_cloudName;
			$password = \Fox\Authorization\Manager::generateRandomPassword();
			$this->_appDatabaseSecureKey = \Fox\Utilities::tokenize($username.':'.$password);
			*/
			$this->_appDatabaseSecureKey = '6E5479324D4939776F5439314D5339317032496C427A30324D51566B5A784F777277626A6D7273343378777173363537';
			$this->_appDatabaseName = $targetDatabaseName;
			
			// Create a Database User
			/* @TODO understand why it fails in the server
			$req = "CREATE USER '$username'@'localhost' IDENTIFIED BY '$password';
					GRANT SELECT, INSERT, UPDATE, DELETE ON *.* TO '$username'@'localhost' IDENTIFIED BY '$password' WITH MAX_QUERIES_PER_HOUR 0 MAX_CONNECTIONS_PER_HOUR 0 MAX_UPDATES_PER_HOUR 0 MAX_USER_CONNECTIONS 0;
					GRANT ALL PRIVILEGES ON $targetDatabaseName . * TO '$username'@'localhost';";
			$connexion->query($sql);
			*/
		} else {
			throw new \Exception("Database $targetDatabaseName already exists");
		}
	}

	/**
	 * 
	 * Build and create index.php file
	 * 
	 */
	private function _buildIndexFile() {
		
		$data[] = '<?php';
		$data[] = '/**';
		$data[] = '* Main Controlling & Rendering';
		$data[] = '* ';
		$data[] = '*/';
		$data[] = 'if (!defined("_PATH_")) {define("_PATH_",dirname(__FILE__));}';
		$data[] = 'require_once("../initialize.php");';
		$data[] = 'Xview::instance(new Xview(SESSION_NAME))->register()->display();';
		$this->write($data,$this->_cloudDirectory.'index.php');
	}
	
	/**
	 * 
	 * Build and create config.php file
	 * 
	 */
	private function _buildConfigFiles() {
		$configDirectory = $this->_cloudDirectory.'config'.DIRECTORY_SEPARATOR;
		if(!is_dir($configDirectory)) {
			mkdir($configDirectory, 0700, true);
		} else {
			//throw new \Exception("Directory $cloudDirectory already exists");
		}
		
		$documentsDirectory = $this->_cloudDirectory.'documents'.DIRECTORY_SEPARATOR;
		if(DIRECTORY_SEPARATOR == '\\') {
			$documentsDirectory = addslashes($documentsDirectory);
		}
		// Constant File
		$companyDirectory = 'images/company';
		$data[] = '<?php';
		$data[] = 'define("APPLICATION_ID",19);';
		$data[] = 'define("_CHARSET_","UTF-8");';
		$data[] = 'define("_PATH_TO_FRAMEWORK_","'._PATH_TO_CLOUD_FRAMEWORK.'");';
		$data[] = 'define("_CORE_ASSETS_","'._PATH_TO_CLOUD_CORE_ASSETS_.'");';
		$data[] = 'define("_CORE_JAVAS_","'._PATH_TO_CLOUD_CORE_JAVAS_.'");';
		$data[] = 'define("_BUNDLES_","'._PATH_TO_HIVE_BUNDLE_.'");';
		$data[] = 'define("_ASSETS_CACHE_DIRECTORY_","'._CLOUD_ASSETS_CACHE_DIRECTORY_.'");';
		$data[] = 'define("_ASSETS_CACHE_URL_","'._CLOUD_ASSETS_CACHE_URL_.'");';
		$data[] = 'define("_ASSETS_","'._CLOUD_ASSETS_.'");';
		$data[] = 'define("LINKEDIN_API_KEY","a548s13tucb8");';
		$data[] = 'define("LINKEDIN_API_SECRET","'._CLOUD_LINKEDIN_API_SECRET_.'");';
		$data[] = 'define("_CLOUD_ACTIVATION_URL","https://signup.hive-solution.com/#language#/activation-compte-utilisateur/activation-compte-utilisateur.html");';
		$data[] = 'define("_DOCUMENTS_",_PATH_."documents".DIRECTORY_SEPARATOR);';
		$data[] = 'define("_MEMORY_DRIVER_","\Fox\Dao\DiskTimeCacheZone");';
		
		$this->write($data,$configDirectory.'const.php');
		// Config.php File
		$data = array();
		// Customizing Settings
		$sessionName = 'hive-'.$this->_cloudName;
		$data[] = '<?php';
		$data[] = 'define("DEV_ENV",false);';
		$data[] = 'define("CACHE_MENU",true);';
		$data[] = 'define("CACHE", true);';
		$data[] = 'define("SESSION_NAME","'.$sessionName.'");';
		$data[] = 'define("SKIP_AUTH", true);';
		$data[] = 'define("COMPANY_ASSETS_URL",_ASSETS_."images/company/");';
		$data[] = 'define("SECURE_COOKIE", true);';
		$data[] = 'define("DEMO_MODE", true);';
		$data[] = 'define("SSO_CONNECTION", true);';
		// Application Assets Specific Directories
		$applicationPrivateKey = \Fox\Utilities::buildRandomKey();
		$data[] = 'define("_APPLICATION_PRIVATE_KEY_","'.$applicationPrivateKey.'");';
		$applicationToken = \Fox\Utilities::buildRandomKey();
		$data[] = 'define("_APPLICATION_TOKEN_","'.$applicationToken.'");';
		$data[] = 'define("_APPLICATION_IMAGES_PROFILE_PATH_",_PATH_."images".DIRECTORY_SEPARATOR."profiles".DIRECTORY_SEPARATOR);';
		$data[] = 'define("_APPLICATION_IMAGES_PROFILE_URL_",_URL_."images/profiles/");';
		$data[] = 'define("_APPLICATION_DEFAULT_PROFILE_PICTURE_",_APPLICATION_IMAGE_URL_."default.gif");';

		$data[] = 'define("_APPLICATION_IMAGES_COMPANIES_PATH_",_PATH_."images".DIRECTORY_SEPARATOR."companies".DIRECTORY_SEPARATOR);';
		$data[] = 'define("_APPLICATION_IMAGES_COMPANIES_URL_",_URL_."images/companies/");';
		$data[] = 'define("_APPLICATION_DEFAULT_COMPANIES_PICTURE_",_APPLICATION_COMPANIES_URL_."default.gif");';
		// Application Database config
		$data[] = '// Databases Config';
		$data[] = 'Fox\Databases::databases()->register(Fox\Databases::DB_FOX, array(';
		$data[] = '	Fox\Databases::PARAM_DRIVER   => "pdo_mysql",';
		$data[] = '	Fox\Databases::PARAM_DB       => "'._CLOUD_CORE_DB_NAME_.'",';
		$data[] = '	Fox\Databases::PARAM_HOST     => "'._CLOUD_DB_HOST_.'",';
		$data[] = '	Fox\Databases::PARAM_SEKEY    => "'._CLOUD_CORE_DB_SECURE_KEY_.'"';
		$data[] = '),array(Fox\Databases::PARAM_USER, Fox\Databases::PARAM_PASSWORD));';
		$data[] = 'Fox\Databases::databases()->register(Fox\Databases::DB_APP, array(';
		$data[] = '	Fox\Databases::PARAM_DRIVER   => "pdo_mysql",';
		$data[] = '	Fox\Databases::PARAM_DB       => "'.$this->_appDatabaseName.'",';
		$data[] = '	Fox\Databases::PARAM_HOST     => "'._CLOUD_DB_HOST_.'",';
		$data[] = '	Fox\Databases::PARAM_SEKEY    => "'.$this->_appDatabaseSecureKey.'"';
		$data[] = '),array(Fox\Databases::PARAM_USER, Fox\Databases::PARAM_PASSWORD));';
		$data[] = '// MySQL Authentication';
		$data[] = 'Fox\Authenticators::instance()->register(Fox\Authenticators::DRIVER_DB);';
		// Email Configuration
		// Emailer
		$data[] = 'define("_EMAIL_","support@hive-solution.com");';
		$data[] = 'define("SEND_MAIL",true);';
		$data[] = 'use Fox\Mailing\Mailer;';
		$data[] = 'Mailer::instance()->register(array(';
		$data[] = 'Mailer::PARAM_FROM => "support@hive-solution.com",';
		$data[] = 'Mailer::PARAM_SMTP => true,';
		$data[] = 'Mailer::PARAM_HOST => "smtp.orinea.com",';
		$data[] = 'Mailer::PARAM_USERNAME => "noreply@orinea.com",';
		$data[] = 'Mailer::PARAM_PASSWORD => "rdRi60eO",';
		$data[] = '));';
		$this->write($data,$configDirectory.'config.php');
	}	

	/**
	 * 
	 * Build all needed application directories
	 * 
	 * @throws \Exception
	 */
	private function _createApplicationDirectories() {
		// Modules
		$this->mkdir($this->_cloudDirectory.'modules');
		// Cache
		$this->mkdir($this->_cloudDirectory.'cache');
		// Logs
		$this->mkdir($this->_cloudDirectory.'logs');
		// Tmp
		$this->mkdir($this->_cloudDirectory.'tmp');
		// Tmp
		$this->mkdir($this->_cloudDirectory.'documents');
		// Images
		$this->mkdir($this->_cloudDirectory.'images');
		// Profile Pictures
		$this->mkdir($this->_cloudDirectory.'images'.DIRECTORY_SEPARATOR.'profiles');
		// Company Pictures
		$this->mkdir($this->_cloudDirectory.'images'.DIRECTORY_SEPARATOR.'companies');
	}
	
	/**
	 * Directory builder
	 * 
	 * @throws \Exception 
	 */
	protected function mkdir($directory,$authorization = 0700) {
		if(!is_dir($directory)) {
			mkdir($directory, $authorization, true);
		} else {
			throw new \Exception("Directory $directory already exists");
		}
	}
	
	/**
	 * Write to file method
	 * 
	 * @param array $data		Data to be transfered
	 * @param string $filename	File be write in it
	 */
	protected function write(array $data,$filename) {
		if(file_exists($filename)) {
			throw new \Exception("File $filename already exists");
			return;
		}
		$endOfLine = "\r\n";
		$fileHandler = fopen($filename, 'w');
		foreach($data as $line) {
			fwrite($fileHandler,$line.$endOfLine);
		}
	}
	
}